import { setUserInfo, getUserInfo, setTokenKey, getTokenKey } from "../../utils/auth";
import { getLocationInfo, getDestinationInfo} from "../../utils/location";
import { showFile, showFiles } from "../../utils/file";
import { checkIsAdmin, createToken, checkIsSuperAdmin, getCosAuth } from "../../utils/user";

var COS = require('cos-wx-sdk-v5');
var QQMapWX = require('../../qqmap/qqmap-wx-jssdk.min');
var qqmapsdk = new QQMapWX({
    key: 'FBJBZ-2ZLC3-W4U3L-36L33-K5II7-QSBO7' // 必填
});
const app = getApp();
var showCount =0;
const markerClassifications = [{
    id: 1,
    isActive: false,
    icon:'../../images/hydrant.png',
    title:'消火栓'
  },
  {
    id: 2,
    isActive: false,
    icon:'../../images/line.png',
    title:'线段标记'
  },
  {
    id: 3,
    isActive: false,
    icon:'../../images/gon.png',
    title:'区域标记'
  },
  {
    id: 4,
    isActive: false,
    icon:'../../images/other.png',
    title:'圆形标记'
  },
  {
    id: 5,
    isActive: false,
    icon:'../../images/station.png',
    title:'消防站'
  },
]
Page({
  data: {
    current_loc_latitude:'',
    current_loc_longitude:'',
    current_loc_title:'',
    city :"西安",
    suggestion:[],
    backfill:'',
    click_item:null,
    markerClassId: 0,
    focus:false,
    markerClassifications,
    searchIcon:'../../images/search_1.png',
    user:{
      username : '请登录',
      enabled : true,
      credits : 100,
      locked : false,
      avatarUrl: '',
      roles : []
    },
    popupShow: false,
    isAdmin: false,
    isSuperAdmin: false,
    pupupData:{
      id:'',
      title: '',
      label: '消火栓',
      status: '',
      region: '',
      latitude:'',
      longitude:'',
      flowRate: 7,
      radius: 0,
      description: '',
      //距离当前点的距离
      distance: '',
      distanceUnit: "米",
      //从当前点开车过去耗时
      duration:'',
      imageList: [],
    }
 
  },
  // 页面切换时会重新执行
  onShow() {
    // 设置当前位置
    getLocationInfo().then(res=>{
      this.setData({
        current_loc_latitude:res.latitude,
        current_loc_longitude:res.longitude,
        current_loc_title: res.title,
        popupShow:false
      })
    }) 
    if(showCount!==0){
      const map = this.selectComponent('.myMap')
      map.clearData()
      map.removeMarkers()
      map.showMarkers()
    }
    showCount++
    if(!getTokenKey()){
      this.userLogin()
    }
  },

  onLoad(){
    this.userLogin()
  },
 
  async userLogin(){
    // 修改为可临时登陆，但无增加权限

    //根据openId获取当前用户信息
    const res = await app.call({
      path:'/wechatUser/me',
      method: 'get'
    })
    
    //请求并存储token
    createToken(app).then((token)=>{
      setTokenKey(token.tokenKey), 
      // 获取Cos资源，注入图像URL
      getCosAuth(app).then( resp => {
        app.globalData.cos = new COS({
          getAuthorization: function (options,callback) {
            // 初始化时不会调用，只有调用 cos 方法（例如 cos.putObject）时才会进入
            // 异步获取临时密钥
            callback({
                TmpSecretId: resp.secretId,
                TmpSecretKey: resp.secretKey,
                // v1.2.0之前版本的 SDK 使用 XCosSecurityToken 而不是 SecurityToken
                SecurityToken: resp.sessionToken,
                // 建议返回服务器时间作为签名的开始时间，避免用户浏览器本地时间偏差过大导致签名错误
                StartTime: resp.startTime, // 时间戳，单位秒，如：1580000000
                ExpiredTime: resp.expiredTime, // 时间戳，单位秒，如：1580000900
            });
          }
        })
        if(res.user){
          const userInfo = res.user
          if(userInfo.file){
            showFile(userInfo.file, app).then(resp1 => {
              userInfo.avatarUrl = resp1.file
              this.setData({
                "user.avatarUrl": resp1.file
              })
              setUserInfo(userInfo)
            })
          }else {
            setUserInfo(userInfo)
          }
          this.setData({
            isAdmin: checkIsAdmin(),
            isSuperAdmin: checkIsSuperAdmin(),
            'user.username' : userInfo.username,
            'user.enabled' : userInfo.enabled,
            'user.credits' : userInfo.credits,
            'user.locked' : userInfo.locked,
            'user.roles' : userInfo.roles
          })
        }
        // //实现登陆
      if(res.code === 4041003){
        setUserInfo(this.data.user)
      }
      })
    }) 
  },

  update(){
    wx.reLaunch({
      url: '/pages/index/index'
    })
    console.log('update')
  },

  // 点击顶部标签分类框
  onMarkerClassificationTap(e) {
    const {id} = e.currentTarget.dataset
    const map = this.selectComponent('.myMap')
    // 移除之前的所有标记
    map.removeAll()
    let markerClassifications = this.data.markerClassifications
    let count = 0
    this.data.markerClassifications.forEach((item, index)=>{
        if(item.id === id) {
          markerClassifications[index].isActive = !markerClassifications[index].isActive 
          if(markerClassifications[index].isActive === true){
            // 展示 分类标签()
            switch(id){
              case 1:
                this.setData({markerClassId: 1})
                map.showMarkers()
                break;
              case 2:
                this.setData({markerClassId: 2})
                map.showMarkers()
                break;
              case 3:
                this.setData({markerClassId: 3})
                map.showMarkers()
                break;
              case 4:
                this.setData({markerClassId: 4})
                map.showMarkers()
                break; 
              case 5:
                  this.setData({markerClassId: 5})
                  break;   
            }

          }else{
            count += 1
          }
        } else{
          markerClassifications[index].isActive = false
          count += 1
        }
        if(count === this.data.markerClassifications.length){
          this.setData({
            markerClassId: 0
          })
        }
    })
    this.setData({
        markerClassifications,
        popupShow: false
    })
    
  },
 
  // 用户点击警情地址后
  backfill: function (e) {
    const{ item } = e.currentTarget.dataset;
    this.setData({
      backfill: item.title
    })
  },
  
  //触发关键词输入提示事件
  getsuggest: function(e) {
      var that = this;
      if(e.detail.value){
        qqmapsdk.getSuggestion({
          keyword: e.detail.value, //用户输入的关键词，可设置固定值,如keyword:'KFC'
          region: this.data.city,
          region_fix: 0 ,
          success: function(res) {//搜索成功后的回调
            var sug = [];
            for (var i = 0; i < res.data.length; i++) {
              sug.push({ // 获取返回结果，放到sug数组中
                title: res.data[i].title,
                id: res.data[i].id,
                addr: res.data[i].address,
                city: res.data[i].city,
                district: res.data[i].district,
                latitude: res.data[i].location.lat,
                longitude: res.data[i].location.lng
              });
            }
            that.setData({ //设置suggestion属性，将关键词搜索结果以列表形式展示
              suggestion: sug,
              searchIcon:'../../images/back.png'
            });
          },
          fail: function(error) {
          },
          complete: function(res) { 
          }
        });
      }else{
        that.setData({ //设置suggestion属性，将关键词搜索结果以列表形式展示
          suggestion: [],
          searchIcon:'../../images/search_1.png'
        });
      }
  },

  //导航到某地
  gotoAddress: function(e){
    const{ item } = e.currentTarget.dataset;
    this.setData({
      suggestion:[],
      backfill:'',
      searchIcon:'../../images/search_1.png'
    })
    const map = this.selectComponent('.myMap')
    map.gotoAddress(item)
  },

  //搜索框icon变换
  onSearchIcon(e){
    const{src} = e.currentTarget.dataset
    if(src === '../../images/back.png'){
      this.setData({
        suggestion:[],
        backfill:'',
        searchIcon:'../../images/search_1.png'
      })
    }
  },

  //点击map时触发 搜索区域消失
  click_Map:function(e){
    this.setData({suggestion: [],backfill:'',searchIcon:'../../images/search_1.png'}) 
  },

  //回到当前位置
  OnCurrentLocationClick:function(){
    const map = this.selectComponent('.myMap')
    map.moveLocation()
  },

  //添加设备
  add_equipment(){
    switch(this.data.markerClassId){
      case 0:
        wx.showModal({
          title: '提示',
          content: '请选择标记类型'
        })
        break;
      case 1:
        wx.navigateTo({
          url: `../addHydrant/index`,
        })
        break;
      case 2:
        wx.navigateTo({
          url: `../addLine/index`,
        })
        break;
      case 3:
        wx.navigateTo({
          url: `../addGon/index`,
        })
        break;
      case 4:
        wx.navigateTo({
          url: `../addCircle/index`,
        })
        break;
      case 5:
          if(this.data.isSuperAdmin){
            wx.navigateTo({
              url: `../fireStation/index`,
            })
          }else{
            wx.showModal({
              title: '抱歉，暂时不提供消防站添加功能',
            })
          }
          
          break;
    } 
  },

  //导航去目的地
  popupClose(){
    this.setData({
      popupShow:false
    }),
    this.clearPopupData
  },

  // 点击marker，触发弹起对话框操作
  markertap(e){
    let clickMarker = e.detail[0]
    this.setData({
      popupShow:true
    })
    console.log(clickMarker)
    switch(clickMarker.type){
      case 'hydrant':
        this.showHydrant(clickMarker.itemId)
        break;
      case 'station':
        this.showStation(clickMarker.itemId)
        break;
      case 'desc':
        this.showDesc(clickMarker)
        break;
      case 'line':
        this.showLine(clickMarker.itemId)
        break;
      case 'gon':
        this.showGon(clickMarker.itemId)
        break;
      case 'circle':
        this.showCircle(clickMarker.itemId)
        break;
    }
  },

  // 展示消火栓
  async showHydrant(itemId){
    this.clearPopupData()
    const resp =await app.call({
      path:`/hydrant/${itemId}`,
      method: 'get',
      header: {
        'X-WX-SERVICE': 'fire-assistant-s',
        'tokens': getTokenKey()//必须添加#######
      },
    })
    this.setData({
      'pupupData.id': resp.id,
      'pupupData.label': '消火栓',
      'pupupData.description': resp.description,
      'pupupData.status': resp.status? "正常":"故障",
      'pupupData.flowRate': resp.flowRate,
      'pupupData.latitude': resp.latitude,
      'pupupData.longitude': resp.longitude
    })
    getDestinationInfo(resp.latitude, resp.longitude).then(res => {
      this.setData({
        'pupupData.title': res.title,
        'pupupData.region': res.region,
        'pupupData.distance': res.distance > 1000 ? Math.ceil(res.distance/1000):res.distance,
        'pupupData.distanceUnit':res.distance > 1000 ? "公里":"米",
        'pupupData.duration': res.duration
      })
    
    })
    showFiles(resp.files, app).then(res =>{
      this.setData({
        'pupupData.imageList': res
      })
    })
  },

  // 展示消防站
  async showStation(itemId){
    this.clearPopupData()
    const resp =await app.call({
      path:`/company/${itemId}`,
      method: 'get',
      header: {
        'X-WX-SERVICE': 'fire-assistant-s',
        'tokens': getTokenKey()//必须添加#######
      },
    })
    this.setData({
      'pupupData.id': resp.id,
      'pupupData.label': '消防站',
      'pupupData.description': resp.description,
      'pupupData.latitude': resp.latitude,
      'pupupData.longitude': resp.longitude,
      'pupupData.title': resp.companyName,
      'pupupData.radius':resp.radius
    })
    getDestinationInfo(resp.latitude, resp.longitude).then(res => {
      this.setData({
        'pupupData.region': res.region,
        'pupupData.distance': res.distance > 1000 ? Math.ceil(res.distance/1000):res.distance,
        'pupupData.distanceUnit':res.distance > 1000 ? "公里":"米",
        'pupupData.duration': res.duration
      })
    })
    showFiles(resp.files, app).then(res =>{
      this.setData({
        'pupupData.imageList': res
      })
    })
  },

  // 展示目的地
  showDesc(marker){
    this.clearPopupData()
    getDestinationInfo(marker.latitude, marker.longitude).then(res =>{
      this.setData({
        'pupupData.title': res.title,
        'pupupData.region': res.region,
        'pupupData.latitude': marker.latitude,
        'pupupData.longitude': marker.longitude,
        'pupupData.label': '目的地',
        'pupupData.distance': res.distance > 1000 ? Math.ceil(res.distance/1000):res.distance,
        'pupupData.distanceUnit':res.distance > 1000 ? "公里":"米",
        'pupupData.duration': res.duration
      })
    })
  },

  // 展示所点击线段
  async showLine(itemId){
    this.clearPopupData()
    const resp =await app.call({
      path:`/line/${itemId}`,
      method: 'get',
      header: {
        'X-WX-SERVICE': 'fire-assistant-s',
        'tokens': getTokenKey()//必须添加#######
      },
    })
    this.setData({
      'pupupData.id': resp.id,
      'pupupData.label': '线段标记',
      'pupupData.description': resp.description,
      'pupupData.latitude': resp.latitude,
      'pupupData.longitude': resp.longitude
    })
    getDestinationInfo(resp.latitude, resp.longitude).then(res => {
      this.setData({
        'pupupData.title': res.title,
        'pupupData.region': res.region,
        'pupupData.distance': res.distance > 1000 ? Math.ceil(res.distance/1000):res.distance,
        'pupupData.distanceUnit':res.distance > 1000 ? "公里":"米",
        'pupupData.duration': res.duration
      })
    })
    showFiles(resp.files, app).then(res =>{
      this.setData({
        'pupupData.imageList': res
      })
    })
  },

  // 展示所点击区域标记
  async showGon(itemId){
    this.clearPopupData()
    const resp =await app.call({
      path:`/polygon/${itemId}`,
      method: 'get',
      header: {
        'X-WX-SERVICE': 'fire-assistant-s',
        'tokens': getTokenKey()//必须添加#######
      },
    })
    this.setData({
      'pupupData.id': resp.id,
      'pupupData.label': '区域标记',
      'pupupData.description': resp.description,
      'pupupData.latitude': resp.latitude,
      'pupupData.longitude': resp.longitude
    })
    getDestinationInfo(resp.latitude, resp.longitude).then(res => {
      this.setData({
        'pupupData.title': res.title,
        'pupupData.region': res.region,
        'pupupData.distance': res.distance > 1000 ? Math.ceil(res.distance/1000) : res.distance,
        'pupupData.distanceUnit':res.distance > 1000 ? "公里":"米",
        'pupupData.duration': res.duration
      })
    })

    showFiles(resp.files, app).then(res =>{
      this.setData({
        'pupupData.imageList': res
      })
    })
  },

  // 展示所点击圆形标记
  async showCircle(itemId){
    this.clearPopupData()
    const resp =await app.call({
      path:`/circle/${itemId}`,
      method: 'get',
      header: {
        'X-WX-SERVICE': 'fire-assistant-s',
        'tokens': getTokenKey()//必须添加#######
      },
    })
    console.log(resp)
    this.setData({
      'pupupData.id': resp.id,
      'pupupData.label': '圆形标记',
      'pupupData.description': resp.description,
      'pupupData.latitude': resp.latitude,
      'pupupData.longitude': resp.longitude,
      'pupupData.radius':resp.radius
    })
    getDestinationInfo(resp.latitude, resp.longitude).then(res => {
      this.setData({
        'pupupData.title': res.title,
        'pupupData.region': res.region,
        'pupupData.distance': res.distance > 1000 ? Math.ceil(res.distance/1000):res.distance,
        'pupupData.distanceUnit':res.distance > 1000 ? "公里":"米",
        'pupupData.duration': res.duration
      })
    })
    showFiles(resp.files, app).then(res =>{
      this.setData({
        'pupupData.imageList': res
      })
    })
  },

  navigateToMarker(){
    if(this.data.pupupData.latitude !== ''){
      wx.openLocation({
        latitude: Number(this.data.pupupData.latitude),
        longitude: Number(this.data.pupupData.longitude),
        name : this.data.pupupData.title
      })
    }  
  },

  //更新功能
  updateContent(){
    const marker = this.data.pupupData
    var imageList =  marker.imageList ? JSON.stringify(marker.imageList) : "[]"
    switch(marker.label){
      case '消火栓':
        wx.navigateTo({
          url: `../addHydrant/index?id=${marker.id}&latitude=${marker.latitude}&title=${marker.title}&longitude=${marker.longitude}&description=${marker.description}&imageList=${encodeURIComponent(imageList)}`,
        })
        break;
      case '线段标记':
        wx.navigateTo({
          url: `../addLine/index?id=${marker.id}&description=${marker.description}}&title=${marker.title}&imageList=${encodeURIComponent(imageList)}`,
        })
        break;
      case '圆形标记':
        wx.navigateTo({
          url: `../addCircle/index?id=${marker.id}&radius=${marker.radius}&title=${marker.title}&latitude=${marker.latitude}&longitude=${marker.longitude}&description=${marker.description}&imageList=${encodeURIComponent(imageList)}`,
        })
        break;
      case '区域标记':
        wx.navigateTo({
          url: `../addGon/index?id=${marker.id}&description=${marker.description}&title=${marker.title}&imageList=${encodeURIComponent(imageList)}`,
        })
        break;
      case '消防站':
        wx.navigateTo({
          url: `../fireStation/index?id=${marker.id}&radius=${marker.radius}&description=${marker.description}&latitude=${marker.latitude}&longitude=${marker.longitude}&title=${marker.title}&imageList=${encodeURIComponent(imageList)}`,
        })
        break;
    }

  },

  clearPopupData(){
    this.setData({
      pupupData:{
        id:'',
        title: '',
        label: '',
        status: '',
        region: '',
        latitude:'',
        longitude:'',
        flowRate: 0,
        description: '',
        //距离当前点的距离
        distance: '',
        //从当前点开车过去耗时
        duration:'',
        images: [
          {
            id:'dfdds',
            image:'../../images/album.png'
          },
          {
            id:'2fdds',
            image:'../../images/album.png'
          },
          {
            id:'21fdds',
            image:'../../images/album.png'
          }
        ],
      }
    })
  }

})

